<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <!-- <el-form-item label="项目名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示" class="movement">
          <el-select v-model="formInline.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="时间">
          <el-date-picker v-model="formInline.value" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增模板</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        max-height="600"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="index"
          align="center"
          :index="indexMethod"
          type="index"
          label="序号"
          width="70"
        >
        </el-table-column>
        <el-table-column prop="category_name" align="center" label="商品分类">
        </el-table-column>
        <el-table-column
          prop="title"
          show-overflow-tooltip
          align="center"
          label="筛选标题和条件"
        >
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.title" :key="index">
              <div>
                {{ item }}<strong> : </strong>{{ scope.row.name[index] }}
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" align="center" label="筛选条件">
        </el-table-column> -->
        <!-- <el-table-column prop="image" align="center" label="项目图片">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.image"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column> -->
        <el-table-column prop="ctime" align="center" label="创建时间">
        </el-table-column>
        <el-table-column prop="status" align="center" label="是否可见">
          <!-- <template slot-scope="scope">
            {{ scope.row.status == "1" ? "可见" : "不可见" }}
          </template> -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="2"
              active-text="是"
              inactive-text="否"
              @change="ifLook(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="sanChu(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 100, 200, 300]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
      :title="titleText"
    >
      <el-form
        :model="formLabelAlign"
        label-width="120px"
        ref="form"
        :rules="rules"
      >
        <div class="oneLine">
          <el-form-item label="商品分类" prop="category_id">
            <el-cascader
              v-model="formLabelAlign.category_id"
              :options="options3"
              popper-class="cascaderParent"
              :props="{
                label: 'name',
                value: 'id',
                checkStrictly: true,
                emitPath: false,
              }"
              clearable
            ></el-cascader>
          </el-form-item>
        </div>
        <div
          class="selectBox"
          v-for="(titleItem, indexOne) in formLabelAlign.filterCriteriaList"
          :key="indexOne"
        >
          <!-- <div>{{ titleItem }},{{ index }}</div> -->
          <div class="oneLine">
            <!-- :label="'筛选条件标题' + indexOne" -->
            <!-- :rules="{
                required: true,
                message: '请输入筛选条件标题',
                trigger: 'blur',
              }" -->
            <el-form-item
              :label="'筛选条件标题'"
              :prop="'filterCriteriaList.' + indexOne + '.title'"
              :rules="{
                required: true,
                message: '请输入筛选条件标题',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="formLabelAlign.filterCriteriaList[indexOne].title"
              ></el-input>
            </el-form-item>
            <i
              class="el-icon-plus"
              @click="addFilterCriteriaTitle(titleItem, indexOne)"
            ></i>
            <i
              v-if="indexOne !== 0"
              class="el-icon-delete"
              @click.prevent="removeFilterCriteriaTitle(indexOne)"
            ></i>
          </div>
          <div
            class="oneLine"
            v-for="(item, indexTwo) in titleItem.name"
            :key="indexTwo"
          >
            <!-- :label="'筛选条件' + indexTwo" -->
            <!-- :rules="{
                required: true,
                message: '请输入筛选条件',
                trigger: 'blur',
              }" -->
            <el-form-item
              :label="'筛选条件'"
              :prop="'filterCriteriaList.' + indexOne + '.name.' + indexTwo"
              :rules="{
                required: true,
                message: '请输入筛选条件',
                trigger: 'blur',
              }"
            >
              <el-input
                v-model="
                  formLabelAlign.filterCriteriaList[indexOne].name[indexTwo]
                "
              ></el-input>
            </el-form-item>
            <i
              class="el-icon-plus"
              @click="addFilterCriteria(indexOne, indexTwo)"
            ></i>
            <i
              v-if="indexTwo !== 0"
              class="el-icon-delete"
              @click.prevent="removeFilterCriteria(indexOne, indexTwo)"
            ></i>
          </div>
        </div>

        <!-- <div class="oneLine">
          <el-form-item label="筛选条件标题" prop="title">
            <el-input
              v-model="formLabelAlign.title"
              placeholder="请输入筛选标题"
            ></el-input>
          </el-form-item>
          <i class="el-icon-plus" @click="addTitle"></i>
          <i class="el-icon-delete" @click="delTitle"></i>
        </div>
        <div class="oneLine">
          <el-form-item label="筛选条件" prop="name">
            <el-input
              v-model="formLabelAlign.name"
              placeholder="请输入筛选条件"
            ></el-input>
          </el-form-item>
          <i class="el-icon-plus" @click="addCondition"></i>
          <i class="el-icon-delete" @click="delCondition"></i>
        </div> -->

        <!-- <div class="oneLine">
          <el-form-item label="项目图片">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFiles"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
              >
                <el-image
                  v-if="imageUrl"
                  class="imageGood"
                  :src="imageUrl"
                  style="width: 360px; height: 180px"
                ></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </div> -->
      </el-form>
      <div class="btnBox">
        <el-button
          type="primary"
          dialogVisible
          class="confirm"
          @click="submitData()"
          >返 回</el-button
        >
        <el-button type="primary" dialogVisible class="confirm" @click="save"
          >确 认</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { opinions, uploadFiles, genreList } from "../../../../utils/api";
import {
  getKXXM,
  addKXXM,
  editKXXM,
  delKXXM,
  getFilterList,
  lookFilterList,
  addFilterList,
  editFilterList,
  delFilterList,
  viewFilterList,
} from "../../../../utils/main";
export default {
  data() {
    return {
      options: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "2",
          label: "否",
        },
      ],
      options3: [],
      formLabelAlign: {
        name: "",
        sort: "",
        avatar: "",
        filterCriteriaList: [
          {
            title: "",
            name: [""],
          },
        ],
        // filterCriteriaTitle1: "",
        // filterCriteria
      },
      fileLimit: 1,
      //   上传图片
      fileList: [],
      headers: { "Content-Type": "multipart/form-data" },
      loading: false,
      token: sessionStorage.getItem("token"),
      dialogVisible: false,
      formInline: {
        status: "",
        name: "",
      },
      tableData: [],
      parameter: {
        common: "",
      },
      total: 0,
      limit: 10,
      page: 1,
      name: "",
      status: "",
      currentPage: 1,
      type: 2,
      imageUrl: "",
      titleText: "",
      parent_id: "0",
      status: "",
      value: "",
      resultTitle: "",
      resultCondition: "",
      filterCriteriaList: [
        {
          title: "",
          name: [""],
        },
      ],
      // rules: {
      //   category_id: [
      //     { required: true, message: "请选择商品分类", trigger: "blur" },
      //   ],
      // },
    };
  },
  methods: {
    //  删除标题一个
    removeFilterCriteriaTitle(item) {
      if (this.formLabelAlign.filterCriteriaList.length > 1) {
        this.formLabelAlign.filterCriteriaList.splice(item, 1);
      } else {
        alert("第一个标题不能删");
      }
      // this.filterCriteriaList.splice(item, 1);
    },
    //  删除条件一个
    removeFilterCriteria(indexOne, indexTwo) {
      // console.log("indexTwpo", indexTwo);
      if (this.formLabelAlign.filterCriteriaList[indexOne].name.length > 1) {
        this.formLabelAlign.filterCriteriaList[indexOne].name.splice(
          indexTwo,
          1
        );
      } else {
        alert("第一个条件不能删");
      }
      // this.filterCriteriaList[indexOne].filterData.splice(indexTwo, 1);
    },
    //添加标题
    addFilterCriteriaTitle(titleItem, indexOne) {
      // console.log(this.formLabelAlign);
      // this.formLabelAlign["filterCriteriaTitle" + titleItem.title] = "";
      // this.filterCriteriaList[indexOne].title = "";
      const filterCriteriaListLength =
        this.formLabelAlign.filterCriteriaList.length;
      this.formLabelAlign.filterCriteriaList.push({
        // title: this.filterCriteriaList[filterCriteriaListLength - 1].title + 1,
        title: "",
        name: [""],
      });
    },
    //添加条件
    addFilterCriteria(indexOne, indexTwo) {
      // this.formLabelAlign["filterCriteria" + indexOne + "—" + indexTwo] = "";
      // this.filterCriteriaList[indexOne].name[indexTwo] = "";
      const filterDataLength =
        this.formLabelAlign.filterCriteriaList[indexOne].name.length;
      this.formLabelAlign.filterCriteriaList[indexOne].name.push(
        ""
        // this.filterCriteriaList[indexOne].name[filterDataLength - 1] + 1
      );
    },

    genreLists() {
      genreList(this.token)
        .then((res) => {
          if (res.data.status) {
            this.options3 = res.data.data;
            this.options3 = this.options3.filter(function (item) {
              return item.id != 234;
            });
            // console.log(this.options3);
            let timer = setTimeout(() => {
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    ifLook(row) {
      // console.log(row.status);
      lookFilterList(
        this.token,
        row.category_id,
        row.status,
        JSON.stringify(row.title)
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: res.data.msg,
            type: "success",
          });
          this.getList();
        }
      });
    },
    // 返回
    submitData() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    //查询
    // onSubmit() {
    //   // this.opinionsS();
    //   this.name = this.formInline.name;
    //   this.status = this.formInline.status;
    //   this.getList();
    // },
    handleReset() {
      this.name = "";
      this.status = "";
      this.formInline.name = "";
      this.formInline.status = "";
      this.getList();
    },
    //详情
    // handleEdit(row) {
    //   this.parameter.common = row.common;
    //   this.dialogVisible = true;
    // },
    //序号
    indexMethod(index) {
      if (this.total < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    //关闭
    handleClose(done) {
      this.$refs.form.resetFields();
      done();
    },
    //条数
    handleSizeChange(val) {
      this.limit = val;
      // this.opinionsS();
      this.getList();
    },
    //页数
    handleCurrentChange(val) {
      this.page = val;
      // this.opinionsS();
      this.getList();
    },
    // 新增
    handleAdd() {
      // this.formLabelAlign = {};
      let arr = {
        category_id: "",
        filterCriteriaList: [
          {
            title: "",
            name: [""],
          },
        ],
        // filterCriteriaTitle1: "",
        // filterCriteria
      };
      this.formLabelAlign = arr;
      this.dialogVisible = true;
      this.titleText = "新增模板";
    },
    // 编辑
    handleEdit(row) {
      if (row.status == 1) {
        this.$message.warning("可见时不能编辑");
        return;
      }
      this.formLabelAlign = row;
      // console.log(row);
      const resultList = row.title.map((item, index) => {
        return {
          title: item,
          name: row.name[index].split(","),
        };
      });
      this.formLabelAlign.filterCriteriaList = resultList;
      // console.log(resultList);
      // console.log(resultList);
      this.dialogVisible = true;
      this.titleText = "编辑模板";
    },
    ifrequired() {
      this.resultTitle = "";
      this.resultCondition = "";
      this.formLabelAlign.filterCriteriaList.forEach((item) => {
        if (item.title == "") {
          this.resultTitle = "false1";
        }
        item.name.forEach((i) => {
          if (i == "") {
            this.resultCondition = "false2";
          }
        });
      });
      console.log(this.resultTitle, "------", this.resultCondition);
    },
    //确定添加
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.ifrequired();
          if (this.resultTitle == "false1") {
            this.$message.warning("请输入筛选标题");
            return;
          }
          if (this.resultCondition == "false2") {
            this.$message.warning("请输入筛选条件");
            return;
          }
          // console.log(this.formLabelAlign, "8888880");
          if (this.formLabelAlign.id != null) {
            // console.log(this.formLabelAlign, "000");
            // 编辑
            editFilterList(
              this.token,
              this.formLabelAlign.id,
              this.formLabelAlign.category_id,
              JSON.stringify(this.formLabelAlign.filterCriteriaList)
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            // console.log(this.formLabelAlign);
            // 新增
            addFilterList(
              // { obj: this.formLabelAlign }
              this.token,
              this.formLabelAlign.category_id,
              JSON.stringify(this.formLabelAlign.filterCriteriaList)
              // this.filterCriteriaList
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "新增成功",
                });
                this.total = res.data.data.count;
                this.formLabelAlign = {};
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除
    sanChu(row) {
      if (row.status == 1) {
        this.$message.warning("可见时不能删除");
        return;
      }
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(row.id);
          delFilterList(this.token, row.category_id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 新增
    handleRemove() {},
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFiles(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          // console.log(res);
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.imageUrl1 = res.data.data.saveurl;
          this.imageUrl = res.data.data.weburl;
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    // 获取列表
    async getList() {
      this.loading = true;
      let res = await getFilterList(this.token, this.page, this.limit);
      if (res.data.status) {
        this.tableData = res.data.data || [];
        this.total = res.data.count;
        // console.log(this.total);
        // console.log(this.tableData, "55555");
        let timer = setTimeout(() => {
          this.loading = false;
          clearTimeout(timer);
        }, 400);
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/login");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
        let timer = setTimeout(() => {
          this.$message.error(res.data.msg);
        }, 5000);
      }
    },
    //列表数据
    // opinionsS() {
    //   this.loading = true;
    //   opinions(
    //     this.token,
    //     this.page,
    //     this.limit,
    //     this.value,
    //     this.formInline.mobile,
    //     this.formInline.name
    //   )
    //     .then((res) => {
    //       if (res.data.status) {
    //         this.tableData = res.data.data.data;
    //         this.total = res.data.data.count;
    //         this.tableData.forEach((item) => {
    //           if (item.avatar) {
    //             item.image = item.avatar;
    //             item.img = "https://bjsf.bjsky.top" + item.avatar;
    //           }
    //           if (item.ctime) {
    //             item.ctime_text = this.getNowTime(item.ctime * 1000);
    //           }
    //         });
    //         let timer = setTimeout(() => {
    //           this.loading = false;
    //           clearTimeout(timer);
    //         }, 400);
    //       } else {
    //         if (res.data.msg == "token失效,请重新进行登录") {
    //           this.$router.push("/login");
    //         }
    //         if (res.data.msg == "此账号没有权限") {
    //           this.$message.error(res.data.msg);
    //           this.loading = false;
    //         }
    //         let timer = setTimeout(() => {
    //           this.$message.error(res.data.msg);
    //         }, 5000);
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err.message);
    //     });
    // },
    // getNowTime(e) {
    //   let date = new Date(e);
    //   let year = date.getFullYear();
    //   let month = date.getMonth() + 1;
    //   let day = date.getDate();
    //   let hour = date.getHours();
    //   let minute = date.getMinutes();
    //   month = month < 10 ? "0" + month : month;
    //   day = day < 10 ? "0" + day : day;
    //   hour = hour < 10 ? "0" + hour : hour;
    //   minute = minute < 10 ? "0" + minute : minute;
    //   return year + "-" + month + "-" + day + " " + hour + ":" + minute;
    // },
  },
  computed: {
    rules() {
      // this.filterCriteriaList.map((item, index) => {});
      return {
        category_id: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      };
    },
  },

  mounted() {
    // this.opinionsS();
    this.getList();
    this.genreLists();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.divFlex {
  display: flex;
  align-items: center;
}
.oneLine {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  margin-bottom: 14px;
  font-size: 24px;
}
.el-icon-delete,
.el-icon-plus {
  margin-left: 15px;
  margin-top: 8px;
  color: rgb(223, 38, 38);
}
.el-icon-plus {
  color: darkgray;
}

.addP {
  font-size: 22px;
  text-align: center;
  margin-bottom: 10px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.btnBox {
  display: flex;
  justify-content: center;
}
/* .selectBox {
  border: 1px solid black;
} */
.cascaderParent .el-cascader-panel .el-scrollbar:first-child .el-radio {
  display: none;
}
</style>